<script setup>
import { Plus, Upload } from '@element-plus/icons-vue'
import {ref, onMounted} from 'vue'
import avatar from '@/assets/default.png'

const uploadRef = ref()
import {useTokenStore} from '@/stores/token.js'

const tokenStore = useTokenStore();

import useUserInfoStore from '@/stores/userInfo.js'

const userInfoStore = useUserInfoStore();
console.log(userInfoStore.info.avatar)
//用户头像地址
const imgUrl = ref('')
// 临时上传的图片URL
const tempImageUrl = ref('')

// 在组件挂载时获取用户头像
onMounted(() => {
  imgUrl.value = userInfoStore.info.avatar || avatar;
})

//图片上传成功的回调函数
const uploadSuccess = (response) => {
  if (response.code === 200) {
    // 只更新临时图片URL，不更新Pinia状态
    tempImageUrl.value = response.data;
    imgUrl.value = response.data; // 仅用于预览
    ElMessage.success('图片上传成功，请点击"保存头像"完成更新');
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
}

//图片上传失败的回调函数
const uploadError = (error) => {
  console.error('上传失败:', error);
  ElMessage.error('图片上传失败');
}

//上传之前的校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
}

import {userAvatarUpdateService} from '@/api/user.js'
import {ElMessage} from 'element-plus'

//头像修改
const updateAvatar = async () => {
  if (!tempImageUrl.value) {
    ElMessage.warning('请先选择并上传图片');
    return;
  }

  try {
    //调用接口
    const result = await userAvatarUpdateService(tempImageUrl.value);

    if (result.code === 200) {
      ElMessage.success(result.msg || '修改成功');
      //修改pinia中的数据
      userInfoStore.setInfo({
        ...userInfoStore.info,
        avatar: tempImageUrl.value
      });
      // 清除临时图片URL
      tempImageUrl.value = '';
    } else {
      ElMessage.error(result.msg || '修改失败');
      // 如果保存失败，恢复原来的头像
      imgUrl.value = userInfoStore.info.avatar || avatar;
    }
  } catch (error) {
    console.error('头像更新失败:', error);
    ElMessage.error('头像更新失败');
    // 如果保存失败，恢复原来的头像
    imgUrl.value = userInfoStore.info.avatar || avatar;
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>更换头像</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="true"
          action="/api/users/avatar"
          name="file"
          :headers="{'Authorization': tokenStore.token}"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip" v-if="!imgUrl">点击上传头像</div>
        <div class="button-group">
          <el-button 
            type="primary" 
            :icon="Plus" 
            size="large" 
            @click="uploadRef.$el.querySelector('input').click()"
          >
            选择图片
          </el-button>
          <el-button 
            type="success" 
            :icon="Upload" 
            size="large" 
            @click="updateAvatar"
            :disabled="!tempImageUrl"
          >
            保存头像
          </el-button>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
      object-fit: cover;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
      line-height: 278px;
    }
  }
}

.upload-tip {
  text-align: center;
  color: #909399;
  margin: 10px 0;
}

.button-group {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}
</style>